<!--
 * @Description: 
 * @version: 
 * @Author: Eve
 * @Date: 2019-09-21 17:25:02
 * @LastEditors: Eve
 * @LastEditTime: 2019-09-21 17:49:32
 -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <h1>Chat</h1>
  <form id="chatForm">
    <label for="formBox">Your Name:</label>
    <input id="formBox" type="text">
    <br />
    <label for="toBox">Send To:</label>
    <input type="text" id="toBox">
    <br />
    <label for="chatBox">Message:</label>
    <input type="text" id="chatBox">
    <button type="submit">Chat</button>
  </form>
  <div id="chatResult"></div>
</body>
<script src="./mediator.js"></script>
<script>
  window.onload = function () {
    let $chatForm = document.querySelector('#chatForm'),
      $chatBox = document.querySelector('#chatBox'),
      $formBox = document.querySelector('#formBox'),
      $toBox = document.querySelector('#toBox'),
      $chatResult = document.querySelector('#chatResult');

    $chatForm.onsubmit = function (e) {
      e.preventDefault();

      // 从UI上获取数据
      let text = $chatBox.value,
        from = $formBox.value,
        to = $toBox.value;
        console.log(text)
        console.log(from)
        console.log(to)

      // 将数据发布到newMessage主题；
      mediator.Publish('newMessage', { message: text, from, to });
    }

    // 将新消息附加到聊天结果记录
    function displayChat(data) {
      console.log(data)
      let date = new Date(),
        msg = data.from + ' said "' + data.message + '" to ' + data.to;

      $chatResult.prepend('' + msg + '(' + date.toLocaleTimeString() + ')')
    }

    // 通过mediator 订阅新提交的newMessage主题
    mediator.Subscribe('newMessage', displayChat);
    mediator.Subscribe('newMessage', logChat)

  }
  // 记录消息日志
  function logChat(data) {

    if (window.console) {
      console.log(data);
    }
  }
</script>

</html>